﻿/****************************************************
    文件：#SCRIPTNAME#.cs
	作者：GHC
    邮箱: 1191775201@qq.com
    日期：#CreateTime#
	功能：联网角色
*****************************************************/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Networking;

public class NetPlayer : NetworkBehaviour
{
    [SyncVar]
    public ChessType chessColor = ChessType.Black;
    private Button retractChessBtn;
    //private Button ReturnBtn;
    bool isDoubleMode = false;

    void Start()
    {
        if (isLocalPlayer)
        {
            CmdSetPlayer();
            if (chessColor == ChessType.Watch)
                return;

            retractChessBtn = GameObject.Find("RetractChess").GetComponent<Button>();
            retractChessBtn.onClick.AddListener(delegate { RetractBtn(); });
        }
    }

    public void RetractBtn()
    {
        CmdRetractBtn();
    }

    [Command]
    public void CmdRetractBtn()
    {
        NetChessBoard.Instance.RetractChess();
    }

    void FixedUpdate()
    {
        if (chessColor == NetChessBoard.Instance.turn && NetChessBoard.Instance.timer > 0.5f && isLocalPlayer
            && NetChessBoard.Instance.PlayerNumber>1)
        {
            PlayerChess();
        }
        if (chessColor != ChessType.Watch && isLocalPlayer && !NetChessBoard.Instance.gameStart)
        {
            NetChessBoard.Instance.GameEnd();
        }
        if (chessColor != ChessType.Watch && isLocalPlayer)
            ChangeBtnColor();
    }

    void ChangeBtnColor()
    {
        if (chessColor == ChessType.Watch)
            return;
        if (NetChessBoard.Instance.turn == chessColor)
            retractChessBtn.interactable = true;
        else
            retractChessBtn.interactable = false;
    }

    public virtual void PlayerChess()
    {
        if (Input.GetMouseButtonDown(0) && !EventSystem.current.IsPointerOverGameObject())
        {
            Vector2 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            //print((int)(pos.x + 7.5f)+ " " + (int)(pos.y + 7.5f));
            CmdChess(pos);
        }
    }

    [Command]
    public void CmdChess(Vector2 pos)
    {
        if (NetChessBoard.Instance.PlayChess(new int[2] { (int)(pos.x + 7.5f), (int)(pos.y + 7.5f) }))
            NetChessBoard.Instance.timer = 0;
    }

    [Command]
    public void CmdSetPlayer()
    {
        NetChessBoard.Instance.PlayerNumber++;
        if (NetChessBoard.Instance.PlayerNumber == 1)
            chessColor = ChessType.Black;
        else if (NetChessBoard.Instance.PlayerNumber == 2)
            chessColor = ChessType.White;
        else
            chessColor = ChessType.Watch;
    }


}
